package com.vayne.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xuerui.zhang
 * @since 2020/4/24 下午4:51
 */
public class NoThreadSafeUseDateFormatDemo {

    static ExecutorService executor = Executors.newFixedThreadPool(10);
    // SimpleDateFormat 线程不安全的类
    static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        // 这里并发的使用同一个工具类: SimpleDateFormat，会产生并发问题，因为 format.format(date) 不是线程安全的
        for (int i = 0; i < 1000; i++) {
            int finInt = i;
            executor.submit(() -> {
                String formatDate = printDateStr(finInt);
                System.out.println("current i = " + finInt + ", date = " + formatDate);
            });
        }
        executor.shutdown();
    }

    private static String printDateStr(int time) {
        Date date = new Date(1000 * time);
        return format.format(date);
    }
}
